<template>
  <div class="mask" v-if="visible">
    <div class="box">
      <div class="title">{{ title }}</div>
      <div><img :src="qRCodeImg" width="256" height="256" /></div>
      <div class="btn" @click="handleConfirm">关闭</div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, computed, nextTick } from 'vue'
import QRCode from 'qrcode'
interface Props {
  visible?: boolean
  url?: string
  title?: string
}

interface Emit {
  (ev: 'confirm'): void
  (ev: 'close'): void
}

const emit = defineEmits<Emit>()

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  url: '',
  title: ''
})
const qRCodeImg = ref<string>('')
const watchURL = computed<string>(() => props.url)
const handleConfirm = () => {
  emit('confirm')
  emit('close')
}

const convertUrlToQRCode = async (url: string) => {
  try {
    const res = await QRCode.toDataURL(url)
    qRCodeImg.value = res
  } catch (err) {
    console.log(err)
  }
}

watch(
  watchURL,
  (value) => {
    if ((!qRCodeImg.value && value) || watchURL.value !== value) {
      nextTick(() => {
        convertUrlToQRCode(value)
      })
    }
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss" scoped>
@use '../styles/dialog.scss' as *;

.btn {
  display: inline-block;
  text-align: center;
  width: 100%;
  height: 42px;
  margin-top: 20px;
  line-height: 42px;
  border-radius: 8px;
  font-size: 16px;
  background-color: var(--primary-color);
  border: 1px solid var(--primary-color);
  color: #fff;
  cursor: pointer;
}
</style>
